import re
from src.ui.i18n import _
from collections import namedtuple
from datetime import datetime, timedelta


Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'text', 'duration', 'start_ms'])

class SRTParser:
    """
    A simple parser for SRT files.
    """
    def __init__(self, file_path):
        self.file_path = file_path
        self.subtitles = []

    def parse(self):
        """
        Parses the SRT file and populates the subtitles list.
        """
        try:
            with open(self.file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 使用正则表达式匹配每个字幕块
            pattern = re.compile(r'(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n(.*?)\n\n', re.DOTALL)
            matches = pattern.findall(content)
            
            for match in matches:
                index = int(match[0])
                start_str = match[1]
                end_str = match[2]
                text = match[3].strip()
                
                # 计算持续时间
                start_time = datetime.strptime(start_str, '%H:%M:%S,%f')
                end_time = datetime.strptime(end_str, '%H:%M:%S,%f')
                duration = (end_time - start_time).total_seconds()
                start_ms = (start_time.hour * 3600 + start_time.minute * 60 + start_time.second) * 1000 + start_time.microsecond / 1000
                
                self.subtitles.append(Subtitle(index, start_str, end_str, text, duration, start_ms))
                
            if not self.subtitles:
                raise ValueError(_("No valid subtitle blocks found in the file."))

        except Exception as e:
            raise RuntimeError(_("Failed to parse SRT file: {}").format(e)) from e

    def get_texts(self):
        """Returns a list of all subtitle texts."""
        return [sub.text for sub in self.subtitles]

    def write(self, output_path, translated_texts):
        """
        Writes a new SRT file with the translated texts.
        """
        if len(translated_texts) != len(self.subtitles):
            raise ValueError(_("The number of translated texts does not match the number of original subtitles."))
            
        try:
            with open(output_path, 'w', encoding='utf-8') as f:
                for i, sub in enumerate(self.subtitles):
                    f.write(f"{sub.index}\n")
                    f.write(f"{sub.start} --> {sub.end}\n")
                    f.write(f"{translated_texts[i]}\n\n")
        except Exception as e:
            raise RuntimeError(_("Failed to write new SRT file: {}").format(e)) from e